<template>
  <div class="skuEdit">
    <el-dialog
      title=""
      :visible.sync="visiable"
      width="65%"
      @close="handleClose"
    >
      <div class="header">
        <el-button
          type="primary"
          size="default"
          @click="handleAddSku"
        >新增</el-button>
      </div>
      <el-table :data="skuList" border stripe size="mini">
        <el-table-column label="#" width="50" type="index" fixed="left" />
        <el-table-column label="图片" width="120">
          <template slot-scope="scope">
            <div>
              <el-upload
                ref="uploadSkuImgs"
                action="http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss"
                :headers="token"
                accept=".png,.jpg,.jpeg,.webp"
                :show-file-list="false"
                :on-success="
                  (res) => {
                    handleSkuImageSuccess(scope.row, res);
                  }
                "
              >
                <img
                  v-if="scope.row.pic"
                  :src="scope.row.pic"
                  alt=""
                  srcset=""
                  class="sku-pic"
                >
                <i v-else class="el-icon-plus upload-sku-icon" />
              </el-upload>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="颜色" width="200">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.color" clearable />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="大小" width="200">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.size" clearable />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="库存" width="200">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.stock" clearable />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="预警库存" width="200">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.lowStock" clearable />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="锁定库存" width="200">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.lockStock" clearable />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="sku编码" width="200">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.skuCode" clearable />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="200">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.price" clearable />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="销量" width="200">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.sale" clearable />
            </div> </template></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <div>
              <el-button
                type="text"
                size="mini"
                style="color: red"
                @click="handleDelSkuItem(scope.row)"
              >
                删除</el-button>
              <el-button
                v-if="scope.row.id"
                type="text"
                size="mini"
                @click="handleUpdateSkuItem(scope.row)"
              >编辑</el-button>

              <el-button
                v-else
                type="text"
                size="mini"
                @click="handleSaveSkuItem(scope.row)"
              >保存</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer">
        <el-button @click="visiable = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid'

import {
  getSkusByProductId,
  delSku,
  updateSkuInfo,
  addProductSkus
} from '@/api/product/index'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      visiable: false,
      productId: '',
      skuList: []
    }
  },
  computed: {
    token() {
      return { token: getToken() }
    }
  },
  methods: {
    // 获取商品的sku列表
    async getSkuList() {
      const { success, data, message } = await getSkusByProductId(
        this.productId
      )
      if (success) {
        this.skuList = data.items.map((item) => {
          const spData = JSON.parse(item.spData)
          return {
            ...item,
            color: spData[0].value,
            size: spData[1].value
          }
        })
      } else {
        this.$message.error(message)
      }
    },
    // 新增
    handleAddSku() {
      this.skuList.push({
        tempId: uuidv4(),
        lockStock: 10, // 锁定库存
        lowStock: 10, // 库存警戒线
        pic: '', // 图片
        price: 0, // 当前价格
        sale: 10, // 销量
        skuCode: '', // sku的编码,手动填写
        stock: 1000, // 库存,
        color: '',
        size: ''
      })
    },
    // 删除
    handleDelSkuItem(item) {
      this.$confirm('此操作会永久删除该数据,是否继续?', '提示', {
        type: 'warning'
      }).then(async() => {
        // 原始sku数据有id
        if (item.id) {
          const { success, message } = await delSku(item.id)
          if (success) {
            this.$message.success('删除成功')
            this.getSkuList()
          } else {
            this.$message.error(message)
          }
        } else {
          // 新增的sku没有id,通过tempId删除
          this.skuList = this.skuList.filter((el) => el.tempId !== item.tempId)
        }
      })
    },

    // 编辑
    async handleUpdateSkuItem(item) {
      const { success, message } = await updateSkuInfo({
        ...item,
        spData: (item.spData = JSON.stringify([
          {
            key: '颜色',
            value: item.color
          },
          {
            key: '大小',
            value: item.size
          }
        ]))
      })
      if (success) {
        this.$message.success('更新成功')
        this.getSkuList()
      } else {
        this.$message.error(message)
      }
    },
    // 保存新增的sku
    async handleSaveSkuItem(item) {
      const obj = {
        ...item,
        productId: this.productId,
        spData: (item.spData = JSON.stringify([
          {
            key: '颜色',
            value: item.color
          },
          {
            key: '大小',
            value: item.size
          }
        ]))
      }
      const { success, message } = await addProductSkus(obj)
      if (success) {
        this.$message.success('保存成功')
      } else {
        this.$message.error(message)
      }
    },

    // 显示
    open(productId) {
      if (productId) {
        this.productId = productId
        this.getSkuList()
      }
      this.visiable = true
    },
    // 上传
    handleSkuImageSuccess(item, res) {
      if (res.success) {
        item.pic = res.data.fileUrl
      }
    },
    // dialog 关闭
    handleClose() {}
  }
}
</script>
<style lang="scss" scoped>
.skuEdit {
  .header {
    display: flex;
    justify-content: flex-end;
  }
  .sku-pic,
  .upload-sku-icon {
    width: 100px;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
